﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Web;
using System.Globalization;
using System.Threading.Tasks;
using GanagroLiteBO;
using GeneralUtilities;


namespace GanagroLite
{
    public partial class FormReportes : WinPart, IreporteView

    {
        private ModoForma modoForma = ModoForma.inicializando;
        private PresenterBO pBO;

        #region Internal Methods
        protected internal override object GetIdValue()
        {
            return "Reportes";
        }

        public override string ToString()
        {
            return "Reportes";
        }
        #endregion

        #region constructors

        private static FormReportes sForm = null;

        public static FormReportes Instance()
        {
            if (sForm == null)
            {
                sForm = new FormReportes();
            }
            return sForm;
        }

        public FormReportes()
        {
            InitializeComponent();
            pBO = new PresenterBO(this);
        }

        #endregion

        #region UI Event Handlers

        private async void FormReportes_Load(object sender, EventArgs e)
         {
             bindingSourceReportes.DataSource = PresenterBO.Reportes;
             bindingSourceOp.DataSource = PresenterBO.Operadores;

             this.comboBoxReportes.ValueMember = "Id";
             this.comboBoxReportes.DisplayMember = "Description";
             this.bindingSourceReportes.Position = 0;

             this.cbFechaF.ValueMember = "Id";
             this.cbFechaF.DisplayMember = "Description";
             this.bindingSourceOp.Position = 1;

             this.dtFechaFinal.Value = System.DateTime.Now;
             this.modoForma = ModoForma.cargada;

         }

        private void comboBoxReportes_SelectedValueChanged(object sender, EventArgs e)
        {
            if (modoForma == ModoForma.cargada)
            {
                if (comboBoxReportes.SelectedValue != null)
                {
                    pBO.PoblarFechasAfinesAlReporte((EnumReportes)Convert.ToByte(comboBoxReportes.SelectedValue.ToString()));

                    this.label1.Visible = false;
                    this.label2.Visible = false;
                    this.label3.Visible = false;
                    this.labelTotal.Visible = false;
                }
            }

        }

        private void FormatGridView(ReportArgs rArgs)
        {
            dbGridView.RowHeadersVisible = false;
            dbGridView.Width = (rArgs.NumeroColumnasGrid * 90 >= 710 ? 710 : rArgs.NumeroColumnasGrid * 80);

            if (dbGridView.Width < 314)
            {
                dbGridView.Width = 314;
            }

            dbGridView.AllowUserToResizeColumns = true;

            if (rArgs.ReportNumber == EnumReportes.MuertesPeriodo)
            {
                dbGridView.ScrollBars = ScrollBars.Vertical;
            }

            bool formatoVvsC = false;   

            foreach (DataGridViewColumn col in dbGridView.Columns)
            {
                
                col.Width = col.Name.Length * 10;

                if (col.Name.ToUpper().StartsWith("CODIGO") || 
                    col.Name.ToUpper().StartsWith("PESO"))
                {
                    col.Width = 60;
                }
                else if (col.Name.ToUpper().Contains("FECHA") )
                {
                    col.Width = 85;
                }
                else if (col.Name.ToUpper().Contains("PRECIO") || col.Name.ToUpper().Contains("COSTO"))
                {
                    col.Width = 65;
                }
                else if (col.Name.ToUpper().StartsWith("VALOR"))
                {
                    col.Width = 80;
                }
                else if (col.Name.ToUpper().Contains("CAUSA"))
                {
                    col.Width = 120;
                }
                else if (col.Name.ToUpper().Contains("G/") || col.Name.ToUpper().Contains("GANANCIA"))
                {
                    col.Width = 70;
                    formatoVvsC = true;
                }
                else 
                {
                    col.AutoSizeMode = DataGridViewAutoSizeColumnMode.ColumnHeader;
                }
            }

            if ((formatoVvsC == false) && (dbGridView.Columns.Count > 0))
            {
               dbGridView.Columns[dbGridView.Columns.Count - 1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            }
        }

        private async void btnConsultar_Click(object sender, EventArgs e)
        {
            try
            {
                // Setup Report parameters
                ReportArgs rArgs       = new ReportArgs();
                rArgs.FechaI           = this.dtFechaInicial.Value.Date;
                rArgs.FechaF           = this.dtFechaFinal.Value.Date;
                rArgs.MatchesFechaI    = checkBoxFI.Checked;
                rArgs.MatchesFechaF    = (EnumCompararFecha)Convert.ToByte(cbFechaF.SelectedValue.ToString());  
                rArgs.IncluirActivos   = checkBoxActivos.Checked;
                rArgs.IncluirInactivos = checkBoxInactivos.Checked;
                rArgs.ReportNumber     = (EnumReportes)Convert.ToByte(comboBoxReportes.SelectedValue.ToString());
                rArgs.Codigos          = this.textBoxCodigos.Text;

                Cursor cCursor = System.Windows.Forms.Cursor.Current;
                System.Windows.Forms.Cursor.Current = Cursors.WaitCursor;

                if (UseDataTables())
                {
                    DataTable DT = pBO.GetReportData(rArgs);
                    bindingSourceMain.DataSource = DT;
                }
                else
                {
                    //TODO: Complete EF transformation for all reports
                    PresenterReportes PR = new PresenterReportes(this);
                    bindingSourceMain.DataSource = await PR.GetGananciaVida(rArgs);
                }

                dbGridView.DataSource = bindingSourceMain;

                bindingSourceMain.ResetBindings(false);

                FormatGridView(rArgs);
                dbGridView.Visible = true;

                System.Windows.Forms.Cursor.Current = cCursor;


            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private static bool UseDataTables()
        {
            // TODO: Read from App settings
            return true;
        }

     private void btnSalir_Click(object sender, EventArgs e)
     {
         bindingSourceMain.CancelEdit();
         this.Close();
     }

 #endregion

     #region Helper methods
     #endregion
     #region IreporteView Members

         public string SummaryData1
         {
             get
             {
                 return this.label1.Text;
             }
             set
             {
                 this.label1.Visible = true;
                 this.label1.Text = value;
             }
         }

         public string SummaryData2
         {
             get
             {
                 return this.label2.Text;
             }
             set
             {
                 this.label2.Text = value;
                 this.label2.Visible = true;
             }
         }

         public string SummaryData3
         {
             get
             {
                 return this.label3.Text;
             }
             set
             {
                 this.label3.Text = value;
                 this.label3.Visible = true;
             }
         }

         public string TotalSemovientes
         {
             get
             {
                 return this.labelTotal.Text;
             }
             set
             {
                 this.labelTotal.Text = value;
                 this.labelTotal.Visible = true;
             }
         }

         public DateTime FechaI
         {
             get
             {
                 return this.dtFechaInicial.Value;
             }
             set
             {
                 this.dtFechaInicial.Value= value;
             }
         }

         public DateTime FechaF
         {
             get
             {
                 return this.dtFechaFinal.Value;
             }
             set
             {
                 this.dtFechaFinal.Value = value;
             }
         }

     #endregion

         private void buttonBrowser_Click(object sender, EventArgs e)
         {
             using (PopupHtml popupHtml = new PopupHtml(((DataTable)bindingSourceMain.DataSource), "Hello", "There"))
             { popupHtml.Show(); }
         }

         private void comboBoxReportes_KeyDown(object sender, KeyEventArgs e)
         {
             if (e.KeyCode == Keys.Enter)
             {
                 btnConsultar_Click(this, EventArgs.Empty);
             }
         }

         private void dbGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
         {
          if (this.dbGridView.Columns[e.ColumnIndex].Name.ToUpper().Contains("CODIGO") == false)
            {
             Int32 myInt;
                if ((e.Value != null) && Int32.TryParse(e.Value.ToString(),out myInt))
                 {
                    if (myInt > 999)
                    {
                      NumberFormatInfo nfi = new CultureInfo("en-US", false).NumberFormat;
                      nfi.NumberDecimalDigits = 0;
                      e.Value =  myInt.ToString("N",nfi);
                      e.FormattingApplied = true;
                    }
                 }
            } 
         }

         private void dtFechaInicial_KeyDown(object sender, KeyEventArgs e)
         {
             try
             {
                 if (e.KeyCode == Keys.F)
                 {
                     this.dtFechaInicial.Value = getFechaFromList();
                 }
             }
             catch (Exception ex)
             {
                 MessageBox.Show(ex.Message);
             }
         }

         private DateTime getFechaFromList()
         {
             DateTime dt = DateTime.Now;
             EnumReportes ReportNumber = (EnumReportes)Convert.ToByte(comboBoxReportes.SelectedValue.ToString());
             using (FormSeleccionFechas fsf = new FormSeleccionFechas(ReportNumber))
             {
                 fsf.ShowDialog();
                 dt = (fsf.FechaSeleccionada <= DateTime.Now.AddYears(-20)) ? dt : fsf.FechaSeleccionada;
             }

             return dt;
         }

         private void dtFechaFinal_KeyDown(object sender, KeyEventArgs e)
         {
             try
             {
                 if (e.KeyCode == Keys.F)
                 {
                     this.dtFechaFinal.Value = getFechaFromList();
                 }
             }
             catch (Exception ex)
             {
                 MessageBox.Show(ex.Message);
             }
         }

         private void textBoxCodigos_TextChanged(object sender, EventArgs e)
         {

         }

    }
 }

